package com.trace.basic;

/**
 * Created by denglw on 2020/1/5.<br/>
 * Desc: 死锁示例
 */
public class DeadLock {

    public static void main(String[] args) {
        DeadRunnable runnable = new DeadRunnable();
        runnable.setFlag(DeadRunnable.FLAG_1);
        new Thread(runnable).start();
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runnable.setFlag(DeadRunnable.FLAG_2);
        new Thread(runnable).start();
    }

    static class DeadRunnable implements Runnable {
        private String flag;
        private final Object LOCK1 = new Object();
        private final Object LOCK2 = new Object();
        static final String FLAG_1 = "FLAG_1";
        static final String FLAG_2 = "FLAG_2";

        void setFlag(String flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            if (FLAG_1.equals(flag)) {
                synchronized (LOCK1) {
                    System.out.println(flag + ":: 已经获取了LOCK1.");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (LOCK2) {
                        System.out.println(flag + ":: 已经获取了LOCK2.");
                    }
                }
            }

            if (FLAG_2.equals(flag)) {
                synchronized (LOCK2) {
                    System.out.println(flag + ":: 已经获取了LOCK2.");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (LOCK1) {
                        System.out.println(flag + ":: 已经获取了LOCK1.");
                    }
                }
            }
        }
    }

}
